<?php

class Tamer_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
	private $_auth;
	private $_acl;
	
	private $_noauth = array('module' => 'safe',
							'controller' => 'login',
							'action' => 'index');
	
	private $_noacl = array('module' => 'default',
							'controller' => 'error',
							'action' => 'privileges');
	
	public function __construct($auth, $acl)
	{
		$this->_auth = $auth;
		$this->_acl = $acl;
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		if ($this->_auth->hasIdentity()) {
			$role = $this->_auth->getIdentity()->role;
		} else {
			$role = 'guest';
		}

		$controller = $request->controller;
		$action 	= $request->action;
		$module 	= $request->module;
		$resource 	= $controller;
		
		if (!$this->_acl->has($resource)) {
			$resource = null;
		}
		
		if (!$this->_acl->isAllowed($role, $resource, $action)) {
			if (!$this->_auth->hasIdentity()) {
				$module = $this->_noauth['module'];
				$controller = $this->_noauth['controller'];
				$action = $this->_noauth['action'];
			} else {
				$module = $this->_noacl['module'];
				$controller = $this->_noacl['controller'];
				$action = $this->_noacl['action'];
			}
		}
		
		$request->setModuleName($module);
		$request->setControllerName($controller);
		$request->setActionName($action);
	}
}
?>
